var async = require('async');
var multiparty = require('multiparty');
var util = require('util');
var fs = require('fs');
var moment = require('moment');
var gm = require('gm').subClass({imageMagick: true});

var connPool = require('./connPool.js');
var LoginBean = require('../jsBean/LoginBean');
var Result = require('../jsBean/Result');

module.exports = {
	register: function (req, res) {
		var pool = connPool();
		
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				res.send('getConnection ERROR');
				return;
			}
			 
			var userAddSql = 'INSERT user(name, account, password, email) VALUES(?, ?, ?, ?);';
			var param = [req.body['name'], req.body['account'], req.body['password'], req.body['email']];
			
			conn.query(userAddSql, param, function (err, rs) {
				if(err) {
					console.log(err.message);
					var errorMessage = err.message;
					res.send({"title": "ADD ERROR", "message": errorMessage });
					return;
				}
				
				
				conn.release();
				res.redirect(307, './login');
			});
		});
	},
	
	login: function (req, res) {
		var pool = connPool();
		
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			 
			var userSelectSql = 'SELECT * FROM user WHERE account=? AND password=?;';
			var param = [req.body['account'], req.body['password']];
			
			conn.query(userSelectSql, param, function (err, rs) {
				// 连接错误
				if(err) {
					console.log(err.message);
					conn.release();
					// ……
					return;
				
				// 连接成功且登录成功
				}else if(rs.length>0 && (rs[0].state == "正常" || rs[0].state == "禁言")) {
					
					// 使用session
					var loginbean = new LoginBean(rs[0].id, rs[0].name, rs[0].account, rs[0].email, rs[0].state, rs[0].createTime, rs[0].status, rs[0].power, rs[0].userPicture);
					req.session.loginbean = loginbean;
					
					var result = new Result();
					result.status = 1;
					
					conn.release();
					res.send(result);
				
				// 连接成功但账号冻结
				}else if(rs.length>0 && rs[0].state == "冻结") {
					
					var result = new Result();
					result.status = 0;
					result.data = {
						message: "您的账号已被冻结！"
					};
					conn.release();
					res.send(result);
					
				// 连接成功但账号密码错误
				}else {
					var result = new Result();
					result.status = 0;
					result.data = {
						message: "账号或密码错误！"
					};
					conn.release();
					res.send(result);
				}
			});
		});
	},
	
	personal: function (req, res, loginbean) {
		
		// 转换时间戳格式
		function timeTransform (time) {
			return moment(time).format('YYYY-MM-DD HH:mm:ss');
		}
		
		var pool = connPool();
		
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			 
			async.waterfall ([
				// 查询用户个人信息
				function (done) {
					var userSelectSql = 'SELECT * FROM user WHERE id=?;';
					var param = [loginbean.id];
					
					conn.query(userSelectSql, param, function (err, rs) {
						// 连接错误
						if(err) {
							console.log(err.message);
							// ……
							return;
						}
						
						var data = {};
						data.userInfo = rs[0];
						
						done(null, data);
					});
				},
				// 查询用户收藏列表
				function (data, done) {
					var userSelectSql = 'SELECT c.*,n.title,n.click,n.comment FROM userCollect AS c JOIN news AS n ON c.newsId=n.id WHERE c.userId=?;';
					var param = [loginbean.id];
					
					conn.query(userSelectSql, param, function (err, rs) {
						// 连接错误
						if(err) {
							console.log(err.message);
							// ……
							return;
						}
						
						rs.forEach(function (item) {
							item.createTime = timeTransform(item.createTime);
						});
						data.userCollect = rs;	
						
						done(null, data);
					});
				},
				// 查询用户评论列表
				function (data, done) {
					var userSelectSql = 'SELECT c.content,c.sendTime,c.newsId,n.title FROM comment AS c JOIN news AS n ON c.newsId = n.id WHERE c.commentId=?;';
					var param = [loginbean.id];
					
					conn.query(userSelectSql, param, function (err, rs) {
						// 连接错误
						if(err) {
							console.log(err.message);
							// ……
							return;
						}
						
						rs.forEach(function (item) {
							item.sendTime = timeTransform(item.sendTime);
						});
						data.userComment = rs;
						
						done(null, data);
					});
				}
				
			], function (err, data) {
				if(err) {
					console.log(err);
					
					return;
				}
				
				conn.release();
				
				res.render('personal', {  
					loginbean: loginbean,
					userInfo: data.userInfo,
					userCollect: data.userCollect,
					userComment: data.userComment
				});
			})
			 
		});
	},
	
	changeInfo: function (req, res, loginbean) {
		var pool = connPool();
		
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			
			var userUpdateSql = 'UPDATE user SET name=?, password=? WHERE id=?;';
			var param = [req.body['name'], req.body['password'], loginbean.id];
			
			conn.query(userUpdateSql, param, function (err, rs) {
				// 连接错误
				if(err) {
					console.log(err.message);
					// ……
					return;
				}
				
				conn.release();
				
				res.redirect(307, '/login');
			});
		});
	},
	
	collect: function (req, res, loginbean) {
		var pool = connPool();
		
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			
			var insertCollectSql = 'INSERT userCollect(newsId,userId) VALUES(?, ?);';
			var param = [req.body['newsId'], loginbean.id];
			
			conn.query(insertCollectSql, param, function (err, rs) {
				// 连接错误
				if(err) {
					console.log(err.message);
					// ……
					return;
				}
				
				conn.release();
				
				var result = new Result();
				result.status = 1;
				
				res.send(result);
			});
		});
	},
	
	uncollect: function (req, res, loginbean) {
		var pool = connPool();
		
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			
			var deleteCollectSql = 'DELETE FROM userCollect WHERE newsId=? AND userId=?;';
			var param = [req.body['newsId'], loginbean.id];
			
			conn.query(deleteCollectSql, param, function (err, rs) {
				// 连接错误
				if(err) {
					console.log(err.message);
					// ……
					return;
				}
				
				conn.release();
				
				var result = new Result();
				result.status = 1;
				
				res.send(result);
			});
		});
	},
	
	userPicture: function (req, res, loginbean) {
		var form = new multiparty.Form();
		form.encoding = 'utf-8';
		form.uploadDir = './uploadtemp/';
		form.maxFilesSize = 2 * 1024 *1024;
	    form.parse(req, function (err, fields, files) {
			var file = files['userPicture'];
			// 获取参数名
			var paraname = file[0].fieldName;
			// 获取原文件名
			var originalFilename = file[0].originalFilename;
			// 获取临时文件的存储路径
			var temPath = file[0].path;
			// 获取文件大小
			var fileSize = file[0].size;
			
			// 构造新存储路径
			var uploadurl = '/img/newsPicture/';
			// 拿到时间戳（字符串类型），拼接文件名，以免上传重名
			var timestamp = new Date().getTime();
			uploadurl += timestamp + originalFilename;
			// 得到新保存路径地址
			var newPath = './public' + uploadurl;
			
			// 准备读写操作
			// 准备读取临时文件路径
			var fileReadStream = fs.createReadStream(temPath);
			// 准备写入正式文件路径
			var fileWriteStream = fs.createWriteStream(newPath);
			// 准备就绪，开启管道流
			fileReadStream.pipe(fileWriteStream);
			// 监听写入事件，一旦写入完毕，执行回调函数
			fileWriteStream.on('close', function () {
				// 删除临时文件夹中的图片
				fs.unlinkSync(temPath);
				console.log('copy over');
				
				
				var pool = connPool();
			
				pool.getConnection(function (err, conn) {
					if(err) {
						console.log(err.message);
						
						return;
					}
					 
					var newsPudateSql = 'UPDATE user SET userPicture=? WHERE id=?;';
					var param = [uploadurl, loginbean.id];
					
					conn.query(newsPudateSql, param, function (err, result) {
						if(err) {
							console.log(err.message);
							
							return;
						}
						
						conn.release();
						
						loginbean.userPicture = uploadurl;
						req.session.loginbean = loginbean;
						
						var result = new Result();
						result.status = 1;
						result.data = {
							uploadurl: uploadurl
						};
						res.send(result);
					});
				});
			});
	    });
	}
};
